
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_rider/event/back_map_pop_car_event.dart';
import 'package:flutter_rider/event/click_manger_pop_event.dart';
import 'package:flutter_rider/event/show_pop_select_car_event.dart';
import 'package:flutter_rider/event/click_stations_event.dart';
import 'package:flutter_rider/main/widgets/dialog/alert_dialog.dart';
import 'package:flutter_rider/main/widgets/ext/u_text.dart';
import 'package:flutter_rider/main/widgets/pop/pop_car_status.dart';
import 'package:flutter_rider/main/widgets/state/state_layout.dart';

import 'package:flutter_rider/main/widgets/ui_constant.dart';
import 'package:flutter_rider/main/models/station_model.dart';
import 'package:flutter_rider/utils/screen_fit.dart';
import 'package:flutter_svg/svg.dart';
import 'package:flutter_rider/api/api.dart';
import 'package:flutter_rider/event/change_stations_event.dart';
import 'package:flutter_rider/generated/r.dart';
import 'package:flutter_rider/main.dart';
import 'package:flutter_rider/utils/extension.dart';
import 'package:flutter_rider/utils/log.dart';
import 'package:flutter_rider/utils/tip.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';

import '../../../event/click_close_stations_event.dart';

class PopNewStationsList extends StatefulWidget {
  String lat;
  String lng;
  String car_no;
  String mode;
  int status;
  int car_id;
  //1:开始调车 2:变更终点
  int lx;

  PopEnterType type;

  PopNewStationsList(this.lat, this.lng, this.car_no, this.mode, this.status,
      this.car_id, this.lx,this.type);

  @override
  State createState() => _PopNewCarListState();
}

class _PopNewCarListState extends State<PopNewStationsList> {
  final _inputController = TextEditingController(text: "");
  dynamic _data;
  final List<StationModel> _result = [];
  //这个是请求了服务器数据根据经纬度排序好的
  final List<StationModel> _dataResult = [];

  //弹框比例
  var _scale = 0.35;
  //是否能点击调车
  var _isEnable = false;

  late StreamSubscription _eventSelectStationsEvent;

  ///站点ID
  late StationModel _selectStationModel;

  ///是否展示列表
  var _isShowList = false;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _eventSelectStationsEvent = eventBus.on<ClickStationsEvent>().listen((event) {
      print("ClickStationsEvent");
      setState(() {
        _isEnable = true;
        _selectStationModel = event.stationModel;
        _inputController.text = _selectStationModel.station_name;
      });
    });

    if (widget.type == PopEnterType.map){
      //显示这个弹框就告诉地图需要在地图上面选点
        eventBus.fire(ShowPopSelectCarEvent(true));
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _eventSelectStationsEvent.cancel();
    print("dispose");
 
    if (widget.type == PopEnterType.map){
      //只要是地图界面打开的，销毁了就告诉地图已经不再地图上面选点流程了
       eventBus.fire(ShowPopSelectCarEvent(false));
    }
   
  }

  @override
  Widget build(BuildContext context) {
    print("我刷新了吗_PopNewCarListState");
    String stText = " ";
    if (widget.status != null) {
      if (widget.status == 3) {
        stText = " 任务中";
      } else if (widget.status == 2 || widget.status == 5) {
        stText = " 空闲中";
      } else if (widget.status == 4) {
        stText = " 调配中";
      }
    }

    var sh = MediaQuery.of(context).size.height;
    var height = sh * _scale;
    if (MediaQuery.of(context).viewInsets.bottom > sh * 0.2) {
      height = sh * (0.3 + _scale);
    }

    return Container(
      height: height,
      padding: EdgeInsets.only(
          left: MediaQuery.of(context).padding.left,
          right: MediaQuery.of(context).padding.right),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.vertical(top: Radius.circular(8.rpx)),
      ),
      child: Column(
        children: [
          8.hspace,
          Container(
            width: 36.rpx,
            height: 5.rpx,
            decoration: BoxDecoration(
              color: Colors.black.withOpacity(0.26),
              borderRadius: BorderRadius.circular(2.rpx),
            ),
          ),
          Container(
              height: 70.rpx,
              alignment: Alignment.center,
              child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    16.wspace,
                    InkWell(child: 
                    SvgPicture.asset(R.image_left,
                        width: 24.rpx, height: 24.rpx),
                      onTap: _backClick,
                    ),
                    4.wspace,
                    Expanded(
                        child: Container(
                      alignment: Alignment.center,
                      child: UText.get("选择目的地", Colors.black, 20.rpx,
                          fw: FontWeight.bold),
                    )),
                    4.wspace,
                    InkWell(child: 
                    SvgPicture.asset(R.image_close,
                        width: 24.rpx, height: 24.rpx),
                      onTap: _closeClick,
                    ),
                    16.wspace,
                  ])),
          // ..._renderCarInfo(),
          // 16.hspace,
          // Container(
          //   margin: EdgeInsets.only(left: 10.rpx, right: 10.rpx),
          //   height: 0.5.rpx,
          //   color: const Color(0xffE7E7E7),
          // ),
          // 16.hspace,
          _renderInput(),
          16.hspace,
          // Container(
          //   margin: EdgeInsets.only(left: 10.rpx, right: 10.rpx),
          //   height: 0.5.rpx,
          //   color: const Color(0xffE7E7E7),
          // ),
          // Visibility(
            // visible: _isShowList,
            // child:
            _isShowList ? 
            Expanded(
              child:
              _getStateLayout(),
            ):Container(
              height: 0,
              child:
              _getStateLayout(),
            // )
          ),

          Container(
            child: Padding(
                padding: EdgeInsets.all(16),
                child: MaterialButton(
                  minWidth: double.infinity,
                  height: 40.rpx,
                  onPressed: _isEnable
                      ? () {
                    _onSubmitClick();
                  }
                      : null,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(4.rpx),
                  ),
                  color: UIColor.color_primary,
                  disabledColor: Colors.black.withOpacity(0.26),
                  child: UText.get("立即调车", Colors.white, 14.rpx),
                )),
          )
        ],
      ),
    );
  }

  StateLayout _getStateLayout() => StateLayout(
                dataCallback: _onDataCallback,
                url: "/home/index",
                childBuilder: _renderContent,
              );

  _backClick() {
    print("返回dispose");
    Navigator.pop(context);
    if (widget.type == PopEnterType.map){
        eventBus.fire(BackMapPopCarEvent());
    }
    else{
        eventBus.fire(ClickMangerPopCarEvent());
    }
    eventBus.fire(ClickCloseStationsEvent());
  }


   _closeClick() {
   print("关闭dispose");
    Navigator.pop(context);
    eventBus.fire(ClickCloseStationsEvent());
  }

  ///立即调车
  _onSubmitClick() {
    print("立即调车");
    CustomAlertDialog.show(context,
            title: _selectStationModel.station_name, content: "确定开始调车吗?", onConfirm: () {
          send_dispatch(_selectStationModel.station_id);
        });
  }

  _onDataCallback(dynamic data) {
    if (_dataResult.isNotEmpty) return; //已经请求过了不请求了
    _data = data;
    List list = [];

    Log.i(_data["station_list"]);
    _data["station_list"].forEach((item) {
      var latlng1 = LatLng(toDouble(widget.lat), toDouble(widget.lng));
      var latlng2 = LatLng(toDouble(item["lat"]), toDouble(item["lng"]));
      var distance = AMapTools.distanceBetween(latlng1, latlng2);
      item["c_distance"] = distance;
      list.add(item);
    });
    list.sort((item1, item2) {
      return (item1["c_distance"] * 100 - item2["c_distance"] * 100).toInt();
    });

    // 转换模型
    List<StationModel> modelList = [];
    list.forEach((element) {
      StationModel mode = StationModel.fromMap(element);
      modelList.add(mode);
    });

    _dataResult.addAll(modelList);

  }

  _onTextChange(String text) {
    print("_onTextChange"+text);
    if (text.isEmpty) {
      setState(() {
        _result.clear();
        // _result.addAll(_data["station_list"]);
        _scale = 0.35;
        _isShowList = false;
        _isEnable = false;
      });
    } else {
      _result.clear();

      for (var station in _dataResult) {
        //把用户输入的转为大写去匹配
        var upperCaseText = text.toUpperCase();
        if (station.station_name.contains(upperCaseText)) {
          _result.add(station);
        }
      }

      // for (int i = 0; i < _data["station_list"].length; i++) {
      //   var station = StationModel.fromMap(_data["station_list"][i]);
      //   var stationName = station.station_name;
      //   stationName = stationName.toLowerCase();
      //   if (stationName.contains(text)) {
      //     _result.add(station);
      //   }
      // }
      _isEnable = false;
      for (var element in _result) {
        if (element.station_name == text){
            //相等
            _selectStationModel = element;
            _isEnable = true;
            break;
        }
      }
      _isShowList = true;

      setState(() {
        _scale = 0.7;
      });
    }
  }

  Widget _renderContent(dynamic data) {
    if (_data["station_list"].length == 0) {
      return Center(
        child: UText.getSubText("暂无数据内容"),
      );
    }
    return ListView.separated(
      itemBuilder: _renderItem,
      itemCount: _result.length,
      separatorBuilder: _renderSeparator,
    );
  }

  Widget _renderInput() {
    return Container(
        color: UIColor.color_content,
        padding: EdgeInsets.symmetric(
          horizontal: 16.rpx,
        ),
        child: Row(crossAxisAlignment: CrossAxisAlignment.center, children: [
          // UText.get("终点", UIColor.color_t1, 16.rpx),
          // 16.wspace,
          Expanded(
            child: Container(
              child: TextField(
                onChanged: _onTextChange,
                controller: _inputController,
                textInputAction: TextInputAction.done,
                maxLength: 20,
                decoration: InputDecoration(
                  constraints:
                      BoxConstraints(minHeight: 44.rpx, maxHeight: 44.rpx),
                  counterText: "",
                  contentPadding: EdgeInsets.symmetric(
                      vertical: 12.rpx, horizontal: 12.rpx),
                  isCollapsed: true,
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(
                        2.rpx,
                      ),
                      borderSide: BorderSide.none),
                  prefixIcon: Padding(
                    padding: EdgeInsets.only(left: 12.rpx, right: 4.rpx),
                    child: Icon(
                      Icons.search,
                      size: 18.rpx,
                      color: Colors.black.withOpacity(0.4),
                    ),
                  ),
                  prefixIconConstraints: BoxConstraints(maxHeight: 16.rpx),
                  hintText: "请搜索目的地",
                  hintStyle: TextStyle(color: Colors.black.withOpacity(0.4)),
                  filled: true,
                  fillColor: UIColor.color_input,
                  suffixIconConstraints: BoxConstraints(maxHeight: 16.rpx),
                  suffixIcon: _inputController.text.isNotEmpty
                      ? Container(
                          padding: EdgeInsets.only(right: 6.rpx),
                          child: GestureDetector(
                            child: Icon(
                              Icons.close,
                              color: UIColor.color_t3,
                              size: 20.rpx,
                            ),
                            onTap: () {
                              _inputController.text = "";
                              _onTextChange("");
                            },
                          ),
                        )
                      : null,
                ),
              ),
            ),
          ),
          // 16.wspace,
        ]));
  }

  Widget _renderSeparator(BuildContext context, int index) {
    return Container(
      margin: EdgeInsets.only(left: 10.rpx, right: 10.rpx),
      height: 0.5.rpx,
      color: const Color(0xffE7E7E7),
    );
  }

  Widget _renderItem(BuildContext context, int index) {
    var item = _result[index];
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      child: SizedBox(
        width: double.infinity,
        height: 64.rpx,
        child: Row(
          children: [
            Container(
              margin: EdgeInsets.only(left: 10.rpx, right: 10.rpx),
              padding: EdgeInsets.only(left: 4.rpx, right: 4.rpx),
              width: 32.rpx,
              height: 32.rpx,
              decoration: const BoxDecoration(
                color: Color(0xffE7E7E7),
                borderRadius: BorderRadius.all(Radius.circular(30.0)),
              ),
              child: SvgPicture.asset(R.image_station2,
                  width: 24.rpx, height: 24.rpx),
            ),
            12.wspace,
            Expanded(
                child: UText.get(item.station_name, Colors.black, 16.rpx,
                    fw: FontWeight.w600)),
            SizedBox(
                width: 100.rpx,
                child: UText.get(
                    index == 0 ? '当前临近站点' : '', UIColor.color_t4, 16.rpx)),
            24.wspace
          ],
        ),
      ),
      onTap: () {
        Log.i("item", item);
        _selectStationModel = item;
        _inputController.text = item.station_name;
        _isEnable = true;
        CustomAlertDialog.show(context,
            title: item.station_name, content: "确定开始调车吗?", onConfirm: () {
          send_dispatch(item.station_id);
        });
        setState(() {
          
        });
      },
    );
  }

  List<Widget> _renderCarInfo() {
    return [
      Row(
        children: [
          24.wspace,
          UText.get("当前模式", Colors.black.withOpacity(0.4), 14.rpx),
          8.wspace,
          Expanded(child: UText.get(widget.mode, Colors.black, 14.rpx)),
          16.wspace,
        ],
      ),
      12.hspace,
      Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          24.wspace,
          UText.get("车辆位置", Colors.black.withOpacity(0.4), 14.rpx),
          8.wspace,
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              UText.get("Lat: ${widget.lat}", Colors.black, 14.rpx),
              2.hspace,
              UText.get("Lng: ${widget.lng}", Colors.black, 14.rpx),
            ],
          )
        ],
      ),
    ];
  }

  send_dispatch(station_id) {
    var url = "/driver/send_dispatch";
    if (widget.lx == 1) {
      url = "/driver/send_dispatch";
    } else {
      url = "/driver/change_destination";
    }

    var json = {};
    json["car_id"] = (widget.car_id).toString();
    json["station_id"] = (station_id).toString();


    Api.submitx(context, url, data: json, progress: false, success: (data) {
      if (widget.lx == 1) {
        Tip.show(widget.car_no + '调配成功');
      } else {
        Tip.show(widget.car_no + '变更成功');
      }
      eventBus.fire(ChangeStationsEvent());
    }, failTip: "提交失败", fail: (_) {});
  }
}
